package com.pingan.haofang.searchcloud.common.rpc;

import java.lang.reflect.Method;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

/**
 * RPC INVOKER注册器
 * 
 * @author LUYI374
 * @date 2017年2月17日
 * @since 1.0.0
 */
@Component
public class RPCInvokerPostProcessor implements BeanPostProcessor {

    private static final String BASE_SCAN_PACKAGE = "com.pingan.haofang.searchcloud";

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!bean.getClass().getName().startsWith(BASE_SCAN_PACKAGE)) {
            return bean;
        }
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
        if (methods != null) {
            for (Method method : methods) {
                RPCExporter rpcExporter = AnnotationUtils.findAnnotation(method, RPCExporter.class);
                if (rpcExporter != null) {
                    RPCInvoker invoker = new RPCInvoker();
                    invoker.setBean(bean);
                    invoker.setDefaultErrorMessage(rpcExporter.defaultErrorMessage());
                    invoker.setMethod(method);
                    String methodName = rpcExporter.value();
                    RPCFactory.register(beanName, methodName, invoker);
                }
            }
        }
        return bean;
    }

}
